<template>
  <div id="articles">
    <!-- 排序选项组件 -->
      <ArticleOrder
      :active-value="activeTab"
      @tab-change="handleTabChange"
    />

    <!-- 文章列表 -->
    <ArticleList
      :articles="articles"
      :loading="loading"
      :error="error"
    />
  </div>
  <ArticlePagination
      :currentPage="currentPage"
      :page_size="pageSize"
      :totalItems="totalItems"
      :totalPages="totalPages"
      @page-change="handlePageChange"
/>

  <div v-if="loading">加载中...</div>
  <div v-if="error">
    {{ error }}
    <button @click="fetchArticles">重试</button>
  </div>
</template>

<script setup>
import ArticleList from '@/components/articles/ArticleList.vue'
import ArticleOrder from '@/components/articles/ArticleOrder.vue'
import ArticlePagination from '@/components/articles/ArticlePagination.vue'

// 响应式数据
const articles = ref([])
const loading = ref(false)
const error = ref(null)
const activeTab = ref('time')
// 页码相关
const currentPage = ref(1)
const pageSize = ref(1) // 每页条数
const totalPages = ref(0) // 总页数
const totalItems = ref(0) // 总条数

// 处理页码变化

const handlePageChange = (page) => {
  currentPage.value = page
  fetchArticles()
}


// 方法
// 处理排序变化
const handleTabChange = (tabId) => {
  activeTab.value = tabId
  articles.value = [] // 清空旧数据
  currentPage.value = 1 // 重置页码
  fetchArticles()
}

// 优化请求方法（保持不变）
const fetchArticles = async () => {
  loading.value = true
  error.value = null
  try {
    const { data } = await axios.get('/api/cms/articles', {
      params: {
      order: activeTab.value,
      page: currentPage.value,
      }
    })
    articles.value = Array.isArray(data.results) ? data.results : []
    pageSize.value = data.page_size
    currentPage.value = data.page
    totalPages.value = data.total_pages
    totalItems.value = data.count
    loading.value = false
  } catch (err) {
    loading.value = false
    error.value = err.message
  }
}

// 生命周期和监听器（保持不变）
onMounted(fetchArticles)
watch([activeTab,currentPage], fetchArticles, { immediate: true })
</script>

<style scoped>
#articles {
  padding: 0;
  display: flex;
  flex-direction: column;
}
</style>
